package vip.ifmm.lehouse.commodity.service.helper;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.*;

/**
 * 线程类
 *
 * @author Red
 * email: 1318944013@qq.com
 * date: 2019/6/21 14:45
 */
@Component
public final class ThreadHelper {

    @Value("${core-size}")
    private int coreSize;

    // 定时任务线程池
    private ScheduledThreadPoolExecutor threadPool;

    @PostConstruct
    public void init() {
        threadPool = new ScheduledThreadPoolExecutor(coreSize);
    }

    /**
     * 执行周期任务
     *
     * @param task 要执行的任务
     */
    public void schedule(Runnable task, long initDelay, long delay) {
        // 延迟initDelay执行第一次，之后每delay执行一次
        threadPool.scheduleWithFixedDelay(task, initDelay, delay , TimeUnit.SECONDS);
    }

    // 销毁工作
    @PreDestroy
    public void destroy() {
        // 关闭线程池
        threadPool.shutdown();
    }
}
